<template>
  <div class="section-tabs">
    <el-tag class="tab-item" v-for="(item, index) in dataList" :key="index" :effect="activedIndex == index ? 'dark' : 'light'" :closable="item.name != 'home'" @click="toPage(item)" @close="close(index)"><c-i18n>{{ item.meta.title }}</c-i18n></el-tag>
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import router from '@/router'
import { useTabStore } from '@/stores/tab'
import { storeToRefs } from 'pinia'

const tab = useTabStore()

const dataList = storeToRefs(tab).tabList

/** 保存 */
const save = (o: any) => {
  if (o.path.startsWith('/dashboard')) {
    const obj = { ...o }
    delete obj.matched
    dataList.value.push(obj)
    tab.$patch({
      tabList: dataList.value
    })
  }
}

if (dataList.value.length === 0) {
  save(router.currentRoute.value)
}

router.beforeEach((to, from, next) => {
  if (dataList.value.every((item: any) => item.path !== to.path)) {
    save(to)
  }
  next()
})

/** 激活索引 */
const activedIndex = computed(() => {
  return dataList.value.findIndex((item: any) => item.path === router.currentRoute.value.path)
})

/** 关闭 */
const close = (index: number) => {
  if (index === activedIndex.value) {
    dataList.value.splice(index, 1)
    if (index <= dataList.value.length - 1) {
      router.push(dataList.value[index].path)
    } else {
      router.push(dataList.value[index - 1].path)
    }
  } else {
    dataList.value.splice(index, 1)
  }
  tab.$patch({
    tabList: dataList.value
  })
}

/** 切换页面 */
const toPage = (item: any) => {
  router.push(item.path)
}
</script>

<style lang="scss" scoped>
.section-tabs {
  display: flex;
  padding: 0 8px;
  box-shadow:
    0 1px 3px 0 rgba(0, 0, 0, 0.12),
    0 0 3px 0 rgba(0, 0, 0, 0.04);
  overflow-x: auto;

  &::-webkit-scrollbar {
    width: 10px;
    height: 4px;
  }

  &::-webkit-scrollbar-thumb {
    height: 50px;
    background-color: #b8b8b8;
    -webkit-border-radius: 6px;
    outline-offset: -2px;
    filter: alpha(opacity=50);
    -moz-opacity: 0.5;
    -khtml-opacity: 0.5;
    opacity: 0.5;
  }

  .tab-item {
    margin: 2px;
    user-select: none;
  }
}
</style>
